// pages/home/home.js
// 节流
const throttle = (fn, delay) => {
  let last
  let timer
  var delay = delay || 200
  return function () {
    let that = this
    let now = +new Date()
    if (last && now - last < delay) {
      Utils.showToast('请勿频繁操作！');
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now;
        fn.apply(that, arguments)
      }, delay)
    } else {
      // 第一次立即执行
      last = now
      fn.apply(that, arguments)
      // 一次操作后不再进行后续 定时器中操作
      clearTimeout(timer)
    }
  }
}
const Utils = require('../../utils/util');
var grantLocation = false;
var grantBluetooth = false;
var hasOpenBluetoothAdapter = false;
var deviceFound = false; //是否已找到设备
var deviceCommunicating = false; //设备正在通信

Page({
  /**
   * 页面的初始数据
   */
  data: {
    headerBgUrl: '/images/ic_bg_streeting.jpg',
    steeringLeftHand: '/images/ic_left_hand.png',
    steeringRightHand: '/images/ic_right_hand.png',
    seatBodyImg: '/images/ic_body.png',
    steeringLeftHandStatus: 0,
    steeringRightHandStatus: 0,
    seatBodyStatus: 0,
    steeringWheelTemp: 0,
    seatTemp: 0,
    selectAreaIndex: -1,
    sliderSize: 16,
    sliderActiveColor: '#007BFF',
    sliderBackgroundColor: '#878787',
    selectBgColor: 'select_bg_cor',
    selectBtnColor: 'select_btn_cor',
    selectFontColor: 'cor_white',
    activeFontColor: 'cor_actived',
    blockColorDefault: '#e9e9e9',
    blockColorActive: '#007BFF',
    steeringWheelTempMin: 35,
    steeringWheelTempMax: 45,
    steeringWheelTempSet: 0,

    seatVentilateSet: 0,
    seatVentilateMin: 50,
    seatVentilateMax: 90,
    seatHeateSet: 0,
    seatHeatMin: 35,
    seatHeatMax: 45,
    massageStrengthSet: 0,
    massageStrengthMin: 35,
    massageStrengthMax: 49,
    massageStatus: 0,
    massageBtnArray: [{
        id: 2,
        message: 'M02',
        name: '波浪按摩'
      },
      {
        id: 6,
        message: 'M06',
        name: '腰部按摩'
      },
      {
        id: 5,
        message: 'M05',
        name: '蝶形按摩'
      },
      {
        id: 3,
        message: 'M03',
        name: '猫步按摩'
      },
      {
        id: 1,
        message: 'M01',
        name: '脉冲按摩'
      },
      {
        id: 4,
        message: 'M04',
        name: '单排按摩'
      }
    ],

    deviceName: 'SHMX-SET9', //默认方向盘的蓝牙设备名称
    deviceId: '',
    serviceId: '',
    characteristicId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.onCheckLocation();
    this.onBluetoothAdapterStateChange();
  },

  /**
   * 选择调节模式：0：调节方向盘；1：调节座椅
   */
  onSelectArea: throttle(function (e) {
    if (e.currentTarget) {
      let {
        index
      } = e.currentTarget.dataset;
      let {
        selectAreaIndex,
        deviceId
      } = this.data;
      if (selectAreaIndex != index) {
        if (deviceFound && deviceCommunicating && deviceId) { //deviceFound为true说明有deviceId，deviceCommunicating为true说明蓝牙正在通信,两个都为true则要先端口蓝牙通信再搜索
          this.writeToDevice('H00');
          if (index == 0) {
            this.writeToDevice('M00');
            this.writeToDevice('F00');
          }
          setTimeout(() => {
            this.onCloseBLEConnection(index);
          }, 500)

        } else {
          this.onResetAndSeekBluetooth(index);
        }
      } else {
        this.onReStart();
      }
    }

  }, 3000),

  /**
   * 如果存在蓝牙设备连接先断开
   * @param {*} index 
   */
  onCloseBLEConnection(index) {
    let that = this;
    let {
      deviceId
    } = that.data;
    if (deviceId) {
      wx.closeBLEConnection({
        deviceId,
        success(res) {
          that.onResetAndSeekBluetooth(index);
        },
        fail(err) {}
      })
    }
  },

  /**
   * 重置并开始搜索蓝牙设备
   * @param {*} index 
   */
  onResetAndSeekBluetooth(index) {
    this.setData({
      selectAreaIndex: index,
      steeringLeftHandStatus: 0,
      steeringRightHandStatus: 0,
      seatBodyStatus: 0,
      seatTemp: 0,
      steeringWheelTemp: 0,
      steeringWheelTempSet: 0,
      seatVentilateSet: 0,
      seatHeateSet: 0,
      massageStrengthSet: 0,
      massageStatus: 0,

      deviceName: index == 0 ? 'SHMX-SET9' : 'HC-08',
      deviceFound: '',
      serviceId: '',
      characteristicId: '',
      deviceId: '',

      headerBgUrl: index == 0 ? '/images/ic_bg_streeting.jpg' : '/images/ic_bg_seat.jpg'
    });
    deviceFound = false;
    deviceCommunicating = false;
    this.onSearchBluetooth();
  },

  onReStart() {
    if (!deviceFound) {
      this.onSearchBluetooth();
    }
    if (!deviceCommunicating && deviceFound) {
      this.onStartConnectDevice();
    }
  },

  /**
   * 检查位置权限，适配低版本手机没开定位搜索不到蓝牙设备
   */
  onCheckLocation() {
    let _this = this;
    grantLocation = false;
    Utils.showLoading('正在初始化...');
    wx.getSetting({
      success(res) {
        Utils.hideLoading();
        if (res.authSetting['scope.userLocation']) {
          _this.onCheckBluetooth();
        } else {
          _this.onAuthorizeLocation();
        }
      }
    });
  },

  /**
   * 定位授权
   */
  onAuthorizeLocation() {
    let _this = this;
    wx.authorize({
      scope: 'scope.userLocation',
      success() {
        _this.onCheckBluetooth();
      },
      fail(errMsg) {
        _this.onAuthorizeLocationFail(errMsg);
      }
    })
  },

  /**
   * 定位授权失败
   * @param {*} errMsg 
   */
  onAuthorizeLocationFail(errMsg) {
    let _this = this;
    Utils.showCommonModal('位置授权失败', '您已拒绝了本次小程序使用的位置授权，本小程序需要使用位置功能，请在设置中开启位置权限,马上设置?', res => {
      if (res.confirm) {
        _this.openSetting('location');
      }
    });
  },

  /**
   * 检查蓝牙权限
   */
  onCheckBluetooth() {
    grantLocation = true;
    let _this = this;
    Utils.showLoading('正在初始化蓝牙...');
    wx.getSetting({
      success(res) {
        Utils.hideLoading();
        if (res.authSetting['scope.bluetooth']) {
          _this.onOpenBluetoothAdapter();
        } else {
          _this.onAuthorizeBluetooth();
        }
      }
    });
  },

  /**
   * 蓝牙授权
   */
  onAuthorizeBluetooth() {
    let _this = this;
    wx.authorize({
      scope: 'scope.bluetooth',
      success() {
        _this.onOpenBluetoothAdapter();
      },
      fail(errMsg) {
        _this.onAuthorizeBluetoothFail(errMsg);
      }
    })
  },

  /**
   * 蓝牙授权失败
   * @param {*} errMsg 
   */
  onAuthorizeBluetoothFail(errMsg) {
    let _this = this;
    Utils.showCommonModal('温馨提示', '您已拒绝了本次小程序使用的蓝牙授权，本小程序需要使用蓝牙功能，请在设置中开启蓝牙权限,马上设置?', res => {
      if (res.confirm) {
        _this.openSetting('bluetooth');
      }
    });
  },

  /**
   * 打开授权设置
   * @param {*} index 
   */
  openSetting(index) {
    let _this = this;
    wx.openSetting({
      success: res => {
        if (index == 'location') {
          if (res.authSetting['scope.userLocation'] || res.authSetting['scope.userLocationBackground']) {
            _this.onAuthorizeBluetooth();
          } else {
            _this.onAuthorizeLocationFail('未授权');
          }
        } else if (index == 'bluetooth') {
          if (res.authSetting['scope.bluetooth']) {
            _this.onOpenBluetoothAdapter();
          } else {
            _this.onAuthorizeBluetoothFail('蓝牙未授权,马上设置？');
          }
        }
      },
      fail: err => {
        if (index == 'location') {
          _this.onAuthorizeLocationFail(err);
        } else if (index == 'bluetooth') {
          _this.onAuthorizeBluetoothFail('蓝牙未授权,马上设置？');
        }
      }
    });
  },

  /**
   * 打开蓝牙
   */
  onOpenBluetoothAdapter() {
    grantBluetooth = true;
    let _this = this;
    wx.openBluetoothAdapter({
      success(res) {
        hasOpenBluetoothAdapter = true;
      },
      fail(err) {
        if (err.errCode == 10001) {
          _this.showOpenBluetooth();
        } else {
          _this.onOpenBluetoothAdapterFail(err);
        }
      }
    })
  },

  /**
   * 蓝牙关闭提示
   */
  showOpenBluetooth() {
    Utils.showCommonModal('温馨提示', '检测到手机蓝牙未打开，请先打开!', res => {});
  },

  /**
   * 蓝牙适配器状态监听
   */
  onBluetoothAdapterStateChange() {
    let _this = this;
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log('adapterState changed, now is', res)
      if (res.available) {
        hasOpenBluetoothAdapter = true;
        _this.onReStart();

      } else {
        hasOpenBluetoothAdapter = false;
        deviceCommunicating = false;
        _this.showOpenBluetooth();
      }
    });
  },

  /**
   * 模拟器打开蓝牙失败提示
   * @param {*} err 
   */
  onOpenBluetoothAdapterFail(err) {
    Utils.showCommonModal('温馨提示', err.errMsg, res => {});
  },

  /**
   * 开始搜索附近蓝牙设备失败提示
   * @param {*} err 
   */
  startBluetoothDevicesDiscoveryFail(err) {
    Utils.showCommonModal('温馨提示', err.errMsg, res => {});
  },

  /**
   * 搜索附近蓝牙设备
   */
  onSearchBluetooth() {
    let _this = this;
    let {
      deviceFound,
      deviceName
    } = _this.data;
    if (!grantLocation) {
      _this.onAuthorizeLocationFail('errMsg');
      return
    }
    if (!grantBluetooth) {
      _this.onAuthorizeBluetoothFail('蓝牙未授权,马上设置？');
      return
    }
    if (!hasOpenBluetoothAdapter) {
      _this.showOpenBluetooth();
      return
    }
    Utils.showLoading('正在搜索...')
    wx.startBluetoothDevicesDiscovery({
      //services: ['FFE0'],
      allowDuplicatesKey: true,
      success: (res) => {
        console.log(res)
      },
      fail(err) {
        _this.startBluetoothDevicesDiscoveryFail(err)
      },
      complete() {
        Utils.hideLoading();
      }
    })

    //监听搜索到新设备的事件
    wx.onBluetoothDeviceFound(function (res) {
      let devices = res.devices;
      if (!deviceFound && devices) {
        let device = devices.find(e => e.name == deviceName);
        console.log(device)
        if (device) {
          _this.onFindDevice(device);
        }
      }
    })
  },

  /**
   * 找到目标设备了
   * @param {*} device 
   */
  onFindDevice(device) {
    let _this = this;
    _this.onStopBluetoothDevicesDiscovery();
    deviceFound = true;
    _this.setData({
      deviceId: device.deviceId
    });
    _this.onStartConnectDevice();
  },

  /**
   * 停止搜寻附近的蓝牙外围设备
   * 若已经找到需要的蓝牙设备并不需要继续搜索时，建议调用该接口停止蓝牙搜索
   */
  onStopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery({
      success(res) {
        console.log(res)
      }
    })
  },

  /**
   * 开始连接蓝牙设备
   */
  onStartConnectDevice() {
    let _this = this;
    let {
      deviceId,
      deviceCommunicating
    } = _this.data;
    if (deviceId && !deviceCommunicating) {
      Utils.showLoading('正在连接目标设备...');
      wx.createBLEConnection({
        deviceId: deviceId,
        success: function (res) {
          _this.onGetBLEDeviceServices(deviceId);
        },
        fail: function (err) {
          _this.handleBLEConnectionError(err);
        },
        complete() {
          Utils.hideLoading();
        }
      });
    }
  },

  /**
   * 连接蓝牙设备异常提示
   * @param {*} err 
   */
  handleBLEConnectionError(err) {
    console.log(err)
    let _this = this;
    Utils.showCommonModal('温馨提示', '异常信息：' + JSON.stringify(err) + '需要重连吗？', res => {
      if (res.confirm) {
        _this.onStartConnectDevice();
      }
    });
  },

  /**
   * 获取蓝牙设备服务列表
   * @param {*} deviceId 
   */
  onGetBLEDeviceServices(deviceId) {
    let that = this;
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function (res) {
        that.getDeviceCharacter(deviceId, res.services);
      },
      fail: function (err) {
        that.handleBLEConnectionError(err);
      }
    })
  },

  /**
   * 获取蓝牙设备特性值
   * @param {*} deviceId 
   * @param {*} services 
   */
  getDeviceCharacter(deviceId, services) {
    let that = this;
    if (services.length <= 0) {
      that.handleBLEConnectionError('该设备暂无服务，无法通信，需要重新连接吗？');
      return
    }
    let service = services.find(e => e.isPrimary && e.uuid.includes('FFE0'));
    if (service) {
      that.queryBLEDeviceCharacteristics(deviceId, service.uuid);
    } else {
      that.handleBLEConnectionError('未找到主服务，需要重新连接吗？');
    }
  },

  /**
   * 查询蓝牙设备特征值，读写操作等的值
   * @param {*} deviceId 
   * @param {*} serviceId 
   */
  queryBLEDeviceCharacteristics(deviceId, serviceId) {
    let that = this;
    that.setData({
      serviceId: serviceId
    })
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: function (res) {
        let characteristics = res.characteristics;
        if (characteristics && characteristics.length > 0) {
          let characteristicId = characteristics[0].uuid;
          that.data.characteristicId = characteristicId;
          if (characteristicId && characteristicId != '') {
            that.onNotifyBLECharacteristicValueChange();
          }
        } else {
          Utils.showFail('抱歉，该设备暂无服务的特征值，无法通信');
        }
      },
      fail: function (err) {
        that.handleBLEConnectionError(err);
      },
      complete: function () {}
    })
  },

  /**
   * 启用蓝牙低功耗设备特征值变化时的 notify 功能，订阅特征
   * 必须先启用 wx.notifyBLECharacteristicValueChange 才能监听到设备 characteristicValueChange 事件
   */
  onNotifyBLECharacteristicValueChange() {
    let that = this;
    let {
      deviceId,
      serviceId,
      characteristicId,
      selectAreaIndex
    } = that.data;
    wx.notifyBLECharacteristicValueChange({
      state: true,
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      success: function (res) {
        console.log(res)
        deviceCommunicating = true;
        Utils.showSuccess('连接成功，正在通信中...');
        that.writeToDevice('R00');
        that.onHandleValueChange();
      }
    })
  },

  /**
   * 监听到设备 characteristicValueChange 事件
   */
  onHandleValueChange() {
    let that = this;
    let {
      selectAreaIndex
    } = that.data;
    wx.onBLECharacteristicValueChange((res) => {
      let result = that.hexToString(res.value);
      let msgArray = result.split(";");
      for (let i = 0, len = msgArray.length; i < len; i++) {
        let cmd = msgArray[i];
        if (cmd.startsWith('NTC1')) {
          if (selectAreaIndex == 0) {
            cmd = cmd.substring(5);
            let num = parseInt(cmd);
            let temp = 0;
            if (num >= 3000) {
              temp = 5;
            } else {
              temp = (3000 - num) / 45 + 11
            }
            console.log('方向盘温度=' + Math.ceil(temp))
            that.setData({
              steeringWheelTemp: Math.ceil(temp),
              seatTemp: 0
            });
          } else {
            console.log('方向盘温度:0')
            that.setData({
              steeringWheelTemp: 0
            });
          }
        } else if (cmd.startsWith('NTC2')) {
          if (selectAreaIndex == 1) {
            cmd = cmd.substring(5);
            let num = parseInt(cmd);
            let temp = 0;
            if (num >= 3000) {
              temp = 5;
            } else {
              temp = (3000 - num) / 45
            }
            console.log('座椅温度=' + Math.ceil(temp))
            that.setData({
              seatTemp: Math.ceil(temp),
              steeringWheelTemp: 0
            });
          } else {
            console.log('座椅温度:0')
            that.setData({
              seatTemp: 0
            });
          }
        } else if (cmd.startsWith('OCS1')) {
          if (selectAreaIndex == 0) { //方向盘
            if (cmd == 'OCS1=0') { //放开方向盘
              that.setData({
                steeringLeftHandStatus: 0,
                steeringRightHandStatus: 0
              });
            } else if (cmd == 'OCS1=1') { //握住方向盘
              that.setData({
                steeringLeftHandStatus: 1,
                steeringRightHandStatus: 1
              });
            }
          } else if (selectAreaIndex == 1) { //座椅
            if (cmd == 'OCS1=0') { //离开座椅
              that.setData({
                seatBodyStatus: 0
              });
            } else if (cmd == 'OCS1=1') { //有人坐上座椅
              that.setData({
                seatBodyStatus: 1
              });
            }
          }
        }
      }
    })
  },

  hexToString(buf) {
    for (var a = buf, i = new DataView(a), n = "", s = 0; s < i.byteLength; s++) {
      n += String.fromCharCode(i.getUint8(s));
    }
    return n;
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    let {
      selectAreaIndex
    } = this.data;
    this.onCloseBLEConnection(selectAreaIndex);
    this.onStopBluetoothDevicesDiscovery();
    wx.closeBluetoothAdapter();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  onHeatSteeringWheel() {
    let {
      selectAreaIndex,
      steeringWheelTempSet,
      steeringWheelTempMin
    } = this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    if (selectAreaIndex == 0) {
      let sendData = 'H00';
      if (steeringWheelTempSet <= steeringWheelTempMin) { //关闭状态则开启
        sendData = 'H01';
        steeringWheelTempMin += 1;
      }
      this.setData({
        steeringWheelTempSet: steeringWheelTempMin
      })
      this.writeToDevice(sendData);
    }
  },

  onChangeSteeringWheel(e) {
    let value = e.detail.value;
    let {
      steeringWheelTempMin
    } = this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    this.setData({
      steeringWheelTempSet: value
    })
    let sendData = 'H00';
    if (steeringWheelTempMin != value) {
      let temp = parseInt(value) - parseInt(steeringWheelTempMin) + 1;
      sendData = 'H' + this.getNumString(temp);
    }
    this.writeToDevice(sendData);
  },

  onSeatVentilate() {
    let {
      selectAreaIndex,
      seatVentilateSet,
      seatVentilateMin,
      seatHeatMin,
      seatHeateSet
    } = this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    if (selectAreaIndex == 1) {
      let sendData = 'F00';
      if (seatVentilateSet <= seatVentilateMin) { //关闭状态则开启
        seatHeateSet = seatHeatMin;
        sendData = 'F01';
        seatVentilateMin += 10;
        this.writeToDevice('H00');
      }
      this.setData({
        seatVentilateSet: seatVentilateMin,
        seatHeateSet: seatHeateSet
      })
      this.writeToDevice(sendData);
    }
  },

  onChangeSeatVentilate(e) {
    let value = e.detail.value;
    let {
      seatVentilateMin,
      seatHeatMin
    } = this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    this.setData({
      seatVentilateSet: value,
      seatHeateSet: seatHeatMin
    })
    let sendData = 'F00';
    if (seatVentilateMin != value) {
      let temp = (parseInt(value) - parseInt(seatVentilateMin)) / 10 + 1;
      sendData = 'F' + this.getNumString(temp);
      this.writeToDevice('H00');
    }
    this.writeToDevice(sendData);
  },

  onSeatHeat() {
    let {
      selectAreaIndex,
      seatHeateSet,
      seatHeatMin,
      seatVentilateMin,
      seatVentilateSet
    } = this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    if (selectAreaIndex == 1) {
      let sendData = 'H00';
      if (seatHeateSet <= seatHeatMin) { //关闭状态则开启
        seatVentilateSet = seatVentilateMin;
        sendData = 'H01';
        seatHeatMin += 1;
        this.writeToDevice('F00');
      }
      this.setData({
        seatHeateSet: seatHeatMin,
        seatVentilateSet: seatVentilateSet
      })
      this.writeToDevice(sendData);
    }
  },

  onChangeSeatHeat(e) {
    let value = e.detail.value;
    let {
      seatHeatMin,
      seatVentilateMin,
    } = this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    this.setData({
      seatHeateSet: value,
      seatVentilateSet: seatVentilateMin
    })
    let sendData = 'H00';
    if (seatHeatMin != value) {
      let temp = parseInt(value) - parseInt(seatHeatMin) + 1;
      sendData = 'H' + this.getNumString(temp);
      this.writeToDevice('F00');
    }
    this.writeToDevice(sendData);
  },

  onChangeMassageStrength(e) {
    let value = e.detail.value;
    this.setData({
      massageStrengthSet: value
    })
    let temp = parseInt((value - 33) / 2);
    let sendData = 'S' + this.getNumString(temp);
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    this.writeToDevice(sendData);
  },

  onHandleMassage(e) {
    let {
      index,
      text
    } = e.currentTarget.dataset;
    let {
      massageStatus,
      selectAreaIndex,
      massageStrengthSet,
      massageStrengthMin
    } = this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    if (selectAreaIndex == 1) {
      if (massageStatus == index) { //相等则关闭
        index = 0;
        text = 'M00';
        massageStrengthSet = 0;
        this.writeToDevice(text);
      } else {
        massageStrengthSet = massageStrengthMin;
        this.writeToDevice('M00');
        this.writeToDevice(text);
        this.writeToDevice('S01');
      }
      this.setData({
        massageStatus: index,
        massageStrengthSet: massageStrengthSet
      })
    }
  },

  up: function () {
    this.onHandleArrowWrite('U01');
  },

  upOff: function () {
    this.onHandleArrowWrite('U00');
  },

  right() {
    this.onHandleArrowWrite('B01');
  },

  rightOff() {
    this.onHandleArrowWrite('B00');
  },

  down() {
    this.onHandleArrowWrite('D01');
  },

  downOff() {
    this.onHandleArrowWrite('D00');
  },

  left() {
    this.onHandleArrowWrite('Y01');
  },

  leftOff() {
    this.onHandleArrowWrite('Y00');
  },

  onHandleArrowWrite(sendData) {
    let _this = this;
    let {
      massageStatus
    } = _this.data;
    if (!hasOpenBluetoothAdapter) {
      this.showOpenBluetooth();
      return
    }
    if (massageStatus == 0) {
      _this.writeToDevice(sendData);
    }
  },

  getNumString(num) {
    if (num < 10) {
      return '0' + num
    } else {
      return num
    }
  },

  writeToDevice(sendData) {
    console.log('sendData=' + sendData)
    let that = this;
    let {
      deviceId,
      serviceId,
      characteristicId
    } = that.data;
    
    if (!deviceFound) {
      Utils.showFail('暂无设备连接!')
      return
    }
    if (!deviceCommunicating) {
      Utils.showFail('蓝牙连接已断开!')
      return
    }
    if (deviceId == '' || serviceId == '' || characteristicId == '') {
      Utils.showToast('该设备缺少通信所需相关参数，无法通信!')
      return
    }
    let buffer = new ArrayBuffer(sendData.length + 2)
    let dataView = new DataView(buffer)
    for (let i = 0; i < sendData.length; i++) {
      dataView.setUint8(i, sendData.charAt(i).charCodeAt())
    }
    dataView.setUint8(sendData.length, 0x0d);
    dataView.setUint8(sendData.length + 1, 0x0a);
    wx.writeBLECharacteristicValue({
      deviceId,
      serviceId,
      characteristicId,
      value: buffer,
      success(res) {
        Utils.showSuccess('发送指令成功')
      },
      fail(err) {
        Utils.showFail('发送指令失败')
        console.log('writeBLECharacteristicValue err:' + JSON.stringify(err))
      },
      complete() {}
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})